from rest_framework import status
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework import serializers
from score.models import Score
from student.models import Student
from course.models import Course
from teacher.models import Teacher
from teacher_course_class.models import TeacherCourseClass
from department.models import Department

# 成绩序列化器（支持课程名称和老师名称）
class ScoreSerializer(serializers.ModelSerializer):
    student_name = serializers.CharField(source='student.name', read_only=True)
    course_name = serializers.CharField(read_only=True)
    teacher_name = serializers.CharField(read_only=True)
    
    # 新增字段：支持通过名称创建课程和老师
    course = serializers.CharField(write_only=True, required=False)  # 课程名称（更新时可选）
    teacher = serializers.CharField(write_only=True, required=False)  # 老师名称（更新时可选）
    student_id = serializers.IntegerField(write_only=True, required=False)  # 学生ID（新增时必填，更新时可选）
    class Meta:
        model = Score
        fields = ['id', 'student', 'student_name', 'student_id', 'course', 'course_name', 
                 'teacher_name', 'teacher', 'value', 'created_at']
        extra_kwargs = {
            'student': {'required': False, 'read_only': True},  # 改为只读，通过student_id处理
            'course': {'required': False},  # 改为可选，因为我们会通过名称创建
            'value': {'required': True}
        }
    
    def validate(self, data):
        """验证成绩数据"""
        # 检查学生是否存在
        student_id = data.get('student_id')
        if student_id and not Student.objects.filter(id=student_id).exists():
            raise serializers.ValidationError({"student_id": "学生不存在"})
        
        # 检查成绩是否在合理范围内
        value = data.get('value')
        if value is not None:
            if value < 0 or value > 100:
                raise serializers.ValidationError({"value": "成绩必须在0-100之间"})
        
        return data
    
    def create_or_get_course(self, course_name):
        """根据课程名称获取或创建课程"""
        course, created = Course.objects.get_or_create(
            name=course_name,
            defaults={
                'credit': 2.0,  # 默认学分
                'description': f'{course_name}课程'
            }
        )
        return course
    
    def create_or_get_teacher(self, teacher_name, student):
        """根据老师名称获取或创建老师"""
        # 获取学生所属的系部
        department = student.department if student.department else Department.objects.first()
        
        teacher, created = Teacher.objects.get_or_create(
            name=teacher_name,
            defaults={
                'sex': True,  # 默认男性
                'title': '讲师',  # 默认职称
                'department': department
            }
        )
        return teacher
    
    def create_or_get_teacher_course_class(self, teacher, course, student):
        """创建或获取教师-课程-班级关系"""
        if student.clazz:
            teacher_course_class, created = TeacherCourseClass.objects.get_or_create(
                teacher=teacher,
                course=course,
                clazz=student.clazz,
                defaults={
                    'school_year': '2024-2025'  # 默认学年
                }
            )
            return teacher_course_class
        return None
    
    def create(self, validated_data):
        """创建成绩记录，自动处理课程和老师的创建"""
        # 提取输入数据
        course_name = validated_data.pop('course')
        teacher_name = validated_data.pop('teacher')
        student_id = validated_data.pop('student_id')
        
        # 获取学生对象
        try:
            student = Student.objects.get(id=student_id)
        except Student.DoesNotExist:
            raise serializers.ValidationError({"student_id": "学生不存在"})
        
        # 获取或创建课程
        course = self.create_or_get_course(course_name)
        
        # 获取或创建老师
        teacher = self.create_or_get_teacher(teacher_name, student)
        
        # 创建教师-课程-班级关系
        self.create_or_get_teacher_course_class(teacher, course, student)
        
        # 检查是否已存在相同学生和课程的成绩记录
        if Score.objects.filter(student=student, course=course).exists():
            raise serializers.ValidationError({"non_field_errors": "该学生此课程的成绩已存在"})
        
        # 设置学生和课程并创建成绩记录
        validated_data['student'] = student
        validated_data['course'] = course
        return super().create(validated_data)
    
    def update(self, instance, validated_data):
        """更新成绩记录，支持更新课程和老师"""
        # 提取输入数据
        course_name = validated_data.pop('course', None)
        teacher_name = validated_data.pop('teacher', None)
        student_id = validated_data.pop('student_id', None)
        
        # 如果提供了student_id，更新学生
        if student_id:
            try:
                student = Student.objects.get(id=student_id)
                validated_data['student'] = student
            except Student.DoesNotExist:
                raise serializers.ValidationError({"student_id": "学生不存在"})
        else:
            student = instance.student
        
        # 如果提供了课程名称，更新课程
        if course_name:
            course = self.create_or_get_course(course_name)
            validated_data['course'] = course
            
            # 如果提供了老师名称，更新老师
            if teacher_name:
                teacher = self.create_or_get_teacher(teacher_name, student)
                self.create_or_get_teacher_course_class(teacher, course, student)
        
        return super().update(instance, validated_data)


# Create your views here.

class ScoreViewSet(ModelViewSet):
    queryset = Score.objects.all()
    serializer_class = ScoreSerializer
    
    # POST - 新增成绩
    def create(self, request, *args, **kwargs):
        """新增成绩记录"""
        try:
            response = super().create(request, *args, **kwargs)
            res = {
                'status': 200,
                'data': {
                    'info': response.data,
                    'message': '成绩添加成功'
                }
            }
            return Response(res, status=status.HTTP_200_OK)
        except Exception as e:
            res = {
                'status': 400,
                'data': {
                    'info': {},
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_400_BAD_REQUEST)
    
    # PUT - 更新成绩
    def update(self, request, *args, **kwargs):
        """更新成绩记录"""
        try:
            response = super().update(request, *args, **kwargs)
            res = {
                'status': 200,
                'data': {
                    'info': response.data,
                    'message': '成绩更新成功'
                }
            }
            return Response(res, status=status.HTTP_200_OK)
        except Exception as e:
            res = {
                'status': 400,
                'data': {
                    'info': {},
                    'message': str(e)
                }
            }
            return Response(res, status=status.HTTP_400_BAD_REQUEST)
    
    # DELETE - 删除成绩
    def destroy(self, request, *args, **kwargs):
        """删除成绩记录"""
        try:
            instance = self.get_object()
            self.perform_destroy(instance)
            res = {
                'status': 200,
                'data': {
                    'info': {},
                    'message': '成绩删除成功'
                }
            }
            return Response(res, status=status.HTTP_200_OK)
        except Exception as e:
            res = {
                'status': 404,
                'data': {
                    'info': {},
                    'message': '成绩记录不存在'
                }
            }
            return Response(res, status=status.HTTP_404_NOT_FOUND)
